package com.hk.security.authentication;

import com.hk.common.util.JsonUtils;
import com.hk.mybatis.query.Result;
import dubhe.token.api.exception.TokenAuthenticationException;
import dubhe.token.api.exception.TokenError;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        final String loginUrl = request.getParameter("loginUrl");
        final String loginHash = request.getParameter("hash");
        if (StringUtils.hasText(loginUrl)) {
            StringBuilder redirectUrlBuilder = new StringBuilder(loginUrl);
            if (StringUtils.hasText(loginHash)) {
                redirectUrlBuilder.append("#").append(loginHash);
            }
            response.sendRedirect(redirectUrlBuilder.toString());
            return;
        }
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        if (exception instanceof TokenAuthenticationException ) {
            TokenAuthenticationException tokenAuthenticationException = (TokenAuthenticationException) exception;
            final TokenError error = tokenAuthenticationException.getError();
            response.setStatus(error.getHttpStatus().value());
            final Result<Object> result = Result
                    .builder()
                    .status(Result.STATUS_FAILED)
                    .message(error.getDescription())
                    .content(error.getErrorCode())
                    .build();
            response.getOutputStream().println(JsonUtils.serializeObject(result));
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            final Result<Object> result = Result
                    .builder()
                    .status(Result.STATUS_FAILED)
                    .message(exception.getMessage())
                    .build();
            response.getOutputStream().println(JsonUtils.serializeObject(result));
        }
    }
}
